import * as echarts from "echarts";
// 导入 markRaw
import { markRaw } from 'vue';

export const useChartAction = (props) => {

  /** charts赋值元素 */
  const chartRef = ref();

  /** chartsd对象 */
  const chart = ref(null);

  /** charts初始化 */
  function initChart() {
    if (isEmpty(props.chartOption)) {
      return;
    }

    if (chart.value?.dispose) {
      chart.value?.dispose();
    }

    chart.value = markRaw(echarts.init(chartRef.value, props.backType));
    setChartOption();
  }

  /** charts设置值 */
  function setChartOption() {
    chart.value.setOption(props.chartOption)
  }

  /** charts重置大小 */
  const resizeHandler = debounce(() => {
    chart.value?.resize()
  }, 10);

  /** 监听数据变化 */
  watch(() => props.chartOption, () => {
    setChartOption();
  }, { deep: true})

  onMounted(() => {
    nextTick(() => {
      initChart();
      addEventListener('resize', resizeHandler);
    })
  })

  onBeforeUnmount(() => {
    removeEventListener('resize', resizeHandler);
  })

  return {
    chartRef,
    chart,
  }
}